package com.leedsoft.service.entity;

import com.google.common.collect.Lists;
import com.leedsoft.common.Enums;
import com.leedsoft.common.JSON;
import com.leedsoft.controller.vo.TaskJsonVo;
import com.leedsoft.domain.*;
import org.springframework.util.Assert;

import java.util.Iterator;
import java.util.List;

/**
 * Created by leeds on 2017/6/20.
 */
public class BranchStep extends Step{
    @Override
    public void wireCoreNode(AidBpmNode node) {
        node.setType(Enums.NodeType.EXCLUSIVE_GATEWAY.getCode().shortValue());
    }

    @Override
    public void genViceNodes() {
        //分支节点，需要将上报上来的taskjson，剥离出已存在节点
        Iterator<TaskJsonVo> it = stepVo.getTaskJsonList().iterator();
        while (it.hasNext()) {
            TaskJsonVo taskJsonVo = it.next();
            if(taskJsonVo.getTaskType() == 1) {
                expInfoTasks.add(taskJsonVo);
                //生成指向已存在节点的Flow
                Assert.notNull(taskJsonVo.getCode(), "参数错误：已存在节点需上传code");
                AidBpmSeqflow flow = newFlow(coreNode.getCode(), taskJsonVo.getCode());
                flow.setExp(taskJsonVo.getExp());
                flow.setLabel(taskJsonVo.getLabel());
                it.remove();
            }
        }
        genNewTasks();
    }

    @Override
    protected void saveTasks() {
        super.saveTasks();
        //保存Step的exp_info
        expInfoTasks.addAll(stepVo.getTaskJsonList());
        List<ExpInfo> expInfoList = Lists.transform(expInfoTasks, input -> {
            ExpInfo expInfo = new ExpInfo();
            expInfo.setExp(input.getExp());
            expInfo.setType(input.getTaskType());
            expInfo.setTaskId(input.getId());
            expInfo.setLabel(input.getLabel());
            return expInfo;
        });
        AidStep step = new AidStep();
        step.setId(stepId);
        step.setExp_info(JSON.gson.toJson(expInfoList));
        stepMapper.updateByPrimaryKeySelective(step);
    }
}
